package com.eostoken.eos_wallet.ui.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.appcompat.widget.AppCompatTextView;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.MapUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseFragment;
import com.eostoken.eos_wallet.bean.OrderIndexBean;
import com.eostoken.eos_wallet.bean.TableRowsBalancesBean;
import com.eostoken.eos_wallet.db.MgpWallet;
import com.eostoken.eos_wallet.eosnet.common.Params;
import com.eostoken.eos_wallet.mvp.mode.AppsModel;
import com.eostoken.eos_wallet.mvp.presenter.AppsPresenterImpl;
import com.eostoken.eos_wallet.mvp.view.AppsView;
import com.eostoken.eos_wallet.ui.fragmentfactory.FragmentFactory;
import com.eostoken.eos_wallet.utils.Constants;
import com.eostoken.eos_wallet.utils.RSAUtils;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.qmuiteam.qmui.layout.QMUILayoutHelper;
import com.qmuiteam.qmui.layout.QMUILinearLayout;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.eostoken.eos_wallet.utils.Constants.BALANCE;
import static com.eostoken.eos_wallet.utils.Constants.EOSIO_TOKEN_CONTRACT_CODE;
import static com.eostoken.eos_wallet.utils.Constants.MGP_SYMBOL;
import static com.eostoken.eos_wallet.utils.Constants.MINING_MORTGAGE;
import static com.eostoken.eos_wallet.utils.Constants.ORDER_INDEX;
import static com.eostoken.eos_wallet.utils.Constants.TABLE_ROWS;
import static com.eostoken.eos_wallet.utils.Constants.bdCurrencyAmount;
import static com.eostoken.eos_wallet.utils.Constants.contractAddress;

public class MortgageBigFragment extends BaseFragment<AppsModel, AppsView, AppsPresenterImpl> implements AppsView {

    @BindView(R.id.topBar)
    QMUITopBar topBar;
    @BindView(R.id.totalMortgageVolumeTv)
    AppCompatTextView totalMortgageVolumeTv;
    @BindView(R.id.accumulativeDestructionTv)
    AppCompatTextView accumulativeDestructionTv;
    @BindView(R.id.layout1)
    QMUILinearLayout layout1;
    @BindView(R.id.yesterdayOrderValueTv)
    AppCompatTextView yesterdayOrderValueTv;
    @BindView(R.id.yesterdayIncentiveTv)
    AppCompatTextView yesterdayIncentiveTv;
    @BindView(R.id.motivateIndexTv)
    AppCompatTextView motivateIndexTv;
    @BindView(R.id.layout2)
    QMUILinearLayout layout2;
    @BindView(R.id.mortgageValueTv)
    AppCompatTextView mortgageValueTv;
    @BindView(R.id.amountMoneyTv)
    AppCompatTextView amountMoneyTv;
    @BindView(R.id.valueTv)
    AppCompatTextView valueTv;
    @BindView(R.id.mortgageStatusTv)
    AppCompatTextView mortgageStatusTv;
    @BindView(R.id.openingTimeTv)
    AppCompatTextView openingTimeTv;
    @BindView(R.id.expectedUnlockTv)
    AppCompatTextView expectedUnlockTv;
    @BindView(R.id.currencyDayValueTv)
    AppCompatTextView currencyDayValueTv;
    @BindView(R.id.layout3)
    QMUILinearLayout layout3;
    @BindView(R.id.layout4)
    QMUILinearLayout layout4;
    @BindView(R.id.button1)
    QMUIRoundButton button1;
    @BindView(R.id.button2)
    QMUIRoundButton button2;
    @BindView(R.id.bottomLayout)
    QMUILinearLayout bottomLayout;
    @BindView(R.id.mortgageStatusLayout)
    RelativeLayout mortgageStatusLayout;
    @BindView(R.id.expectedUnlockLayout)
    RelativeLayout expectedUnlockLayout;
    @BindView(R.id.openingTimeLayout)
    RelativeLayout openingTimeLayout;


    private MgpWallet wallet;
    private String code;
    private String action;
    private String privateKey;
    private String accountName;
    private String type;
    private int mRadius;
    private String remaining;
    private String mMgpNum = "0.0000";

    private OrderIndexBean orderIndexBean;

//    private static class LazyHolder {
//        private static final MortgageBigFragment INSTANCE = new MortgageBigFragment();
//    }
//
//    public static final MortgageBigFragment getInstance() {
//        return LazyHolder.INSTANCE;
//    }

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_mortgage_big;
    }

    @Override
    protected void initData() {
        mRadius = QMUIDisplayHelper.dp2px(getContext(), 10);
        wallet = WalletUtils.getCurrentWallet(getActivity());
        privateKey = wallet.getPrivateKey();
        accountName = wallet.getCurrentAccountName();
        presenter.requestCurrencyBalance(Params.getBalancePamars("eosio.token", EOSIO_TOKEN_CONTRACT_CODE, MGP_SYMBOL));
    }

    public void lazyLoad() {
        try {
            //(code: "proltniouser", action: "redeem", json: jsonString!) ["account":SingleOne.shared.accountName]
//            code = "proltniouser";
//            action = "redeem";
//            Map mapTransaction = MapUtils.newHashMap();
//            mapTransaction.put("account", accountName);
//            String jsonData = GsonUtils.toJson(mapTransaction);
//            presenter.sendTransaction(action, privateKey, accountName, code, jsonData);

            //scope: "proltniouser", code: "proltniouser", table: "balances", table_key: "", json: true, lowerBound: "",
            // upperBound: SingleOne.shared.accountName, limit: nil)
            Map mapTableRows = MapUtils.newHashMap();
            mapTableRows.put("scope", contractAddress);
            mapTableRows.put("code", contractAddress);
            mapTableRows.put("table", "balances");
            mapTableRows.put("json", true);
            mapTableRows.put("table_key", "");
            mapTableRows.put("lower_bound", accountName);
            mapTableRows.put("upper_bound", accountName);
            presenter.requestTableRows(mapTableRows);

            Map mapOrderIndex = MapUtils.newHashMap();
            mapOrderIndex.put("address", accountName);
            String jsonData2 = GsonUtils.toJson(mapOrderIndex);
            String content = RSAUtils.encrypt(jsonData2);
            presenter.requestPortData(content, ORDER_INDEX);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initView(View contentView) {
        topBar.setTitle(StringUtils.getString(R.string.str_mango_hashrate_n));
        topBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popOrFinish();
            }
        });
        layout1.setRadius(mRadius);
        layout2.setRadius(mRadius);
        layout3.setRadius(mRadius, QMUILayoutHelper.HIDE_RADIUS_SIDE_BOTTOM);
        layout4.setRadius(mRadius, QMUILayoutHelper.HIDE_RADIUS_SIDE_BOTTOM);
    }

    private void updataView() {
        if (orderIndexBean != null) {
            OrderIndexBean.DataBean dataBean = orderIndexBean.getData();
            if (dataBean != null) {
                totalMortgageVolumeTv.setText(dataBean.getSysMgpNum());
                OrderIndexBean.DataBean.YesterdayOrderBean yesterdayOrderBean = dataBean.getYesterdayOrder();
                if (yesterdayOrderBean != null) {
                    yesterdayOrderValueTv.setText("$" + (ObjectUtils.isEmpty(yesterdayOrderBean.getOrderValue()) ? "0" : yesterdayOrderBean.getOrderValue()));
                    yesterdayIncentiveTv.setText((ObjectUtils.isEmpty(yesterdayOrderBean.getMoney()) ? "0" : yesterdayOrderBean.getMoney()) + MGP_SYMBOL);
                    motivateIndexTv.setText((ObjectUtils.isEmpty(yesterdayOrderBean.getPro()) ? "0" : yesterdayOrderBean.getPro()) + "%");
                }
                OrderIndexBean.DataBean.OrderBean orderBean = dataBean.getOrder();
                if (orderBean != null) {
                    if (ObjectUtils.isEmpty(orderBean.getLockStatus())) {
                        mortgageStatusLayout.setVisibility(View.GONE);
                    } else {
                        mortgageStatusTv.setText(orderBean.getLockStatus());
                    }
                    mortgageValueTv.setText(ObjectUtils.isEmpty(orderBean.getOrderLevel()) ? "M0" : orderBean.getOrderLevel());
                    if (ObjectUtils.isEmpty(orderBean.getCreateTime())) {
                        openingTimeLayout.setVisibility(View.GONE);
                    } else {
                        openingTimeTv.setText(orderBean.getCreateTime());
                    }
                    if (ObjectUtils.isEmpty(orderBean.getUnlockTime())) {
                        expectedUnlockLayout.setVisibility(View.GONE);
                    } else {
                        expectedUnlockTv.setText(orderBean.getUnlockTime());
                    }
                    String dailyPro = orderBean.getDailyPro();
                    String mDailyPro = null;
                    if (!ObjectUtils.isEmpty(dailyPro)) {
                        BigDecimal dailyProDecimal = new BigDecimal(dailyPro);
                        mDailyPro = dailyProDecimal.multiply(new BigDecimal("100")).stripTrailingZeros().toPlainString();
                    }
                    currencyDayValueTv.setText(ObjectUtils.isEmpty(mDailyPro) ? "0" : (mDailyPro + "%"));
                    valueTv.setText("$" + (ObjectUtils.isEmpty(orderBean.getOrderValue()) ? "0" : orderBean.getOrderValue()));
                    mMgpNum = orderBean.getMgpNum();
                    amountMoneyTv.setText((ObjectUtils.isEmpty(mMgpNum) ? "0" : orderBean.getMgpNum()) + "MGP");
                }
            }
        }
    }

    @OnClick({R.id.button1, R.id.button2})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        boolean isButton1 = true;
        switch (view.getId()) {
            case R.id.button1:
                isButton1 = true;
                if (button2.getVisibility() == View.GONE) {
                    mMgpNum = "0";
                }
                bundle.putString("mgpNum", mMgpNum);
                break;
            case R.id.button2:
                isButton1 = false;
                bundle.putString("remaining", remaining);
                break;
        }
        bundle.putString("type", isButton1 ? button1.getText().toString() : button2.getText().toString());
        bundle.putBoolean("isMortgage", isButton1);
        Fragment fragment = FragmentFactory.getInstatic().getFragment(MINING_MORTGAGE);
        fragment.setArguments(bundle);
        FragmentUtils.replace(getFragmentManager(), fragment, R.id.frag_container, "MiningMortgageFragment", true);
    }

    @Override
    public void updateView(Object data, int responseSuccessCode) {
        LogUtils.dTag("Mortgage==", "updateView data = " + data + " responseSuccessCode = " + responseSuccessCode);
        switch (responseSuccessCode) {
            case BALANCE://["161.4881 MGP"]
                String b = "0";
                if (!ObjectUtils.isEmpty(data)) {
                    if (data.toString().contains("MGP")) {
                        b = data.toString().split(" ")[0].replace("[\"", "");
                    }
                }
                if (ObjectUtils.isEmpty(b)) {
                    b = "0";
                }
                BigDecimal balance = new BigDecimal(b);
                accumulativeDestructionTv.setText(b);
                break;
            case ORDER_INDEX:
                orderIndexBean = GsonUtils.fromJson(data.toString(), OrderIndexBean.class);
                if (orderIndexBean.getCode() == 0) {
                    updataView();
                } else {
                    ToastUtils.showShort(orderIndexBean.getMsg());
                }
                break;
            case TABLE_ROWS:
                if (!ObjectUtils.isEmpty(data)) {
                    TableRowsBalancesBean tableRowsBalancesBean = GsonUtils.fromJson(data.toString(), TableRowsBalancesBean.class);
                    if (tableRowsBalancesBean != null) {
                        List<TableRowsBalancesBean.RowsBean> rowsBeanList = tableRowsBalancesBean.getRows();
                        if (ObjectUtils.isEmpty(rowsBeanList)) {
                            remaining = "0";
                        } else {
                            TableRowsBalancesBean.RowsBean rowsBean = rowsBeanList.get(0);
                            remaining = rowsBean.getRemaining().split(" ")[0];
                        }
                        BigDecimal bdRemaining = new BigDecimal(remaining);
                        // 如果指定的数与参数相等返回0。
                        // 如果指定的数小于参数返回 -1。
                        // 如果指定的数大于参数返回  1。
                        if (bdRemaining.compareTo(BigDecimal.ZERO) > 0) {
                            button1.setVisibility(View.VISIBLE);
                            button2.setVisibility(View.VISIBLE);
                            button1.setText(getString(R.string.str_additional_mortgage));
                        } else {
                            button1.setVisibility(View.VISIBLE);
                            button2.setVisibility(View.GONE);
                            button1.setText(getString(R.string.str_mortgage_initiated));
                        }
                    }
                }
                break;
        }
    }

    @Override
    public void onFailure(Object data, int responseFailCode) {
        LogUtils.dTag("Mortgage==", "onFailure data = " + data + " responseFailCode = " + responseFailCode);
        switch (responseFailCode) {
            case ORDER_INDEX:
                ToastUtils.showShort(data.toString());
                break;
        }
    }

    @Override
    public void updateView(boolean success, Object o1, Object o2) {
        LogUtils.dTag("Mortgage==", "success = " + success + " o1 = " + o1 + " o2 = " + o2);
        if (!success) {
//            button1.setVisibility(View.VISIBLE);
//            button2.setVisibility(View.GONE);
//            button1.setText(getString(R.string.str_mortgage_initiated));
        }
    }

    @Override
    public AppsModel createModel() {
        return new AppsModel();
    }

    @Override
    public AppsView createView() {
        return this;
    }

    @Override
    public AppsPresenterImpl createPresenter() {
        return new AppsPresenterImpl(getActivity());
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void onResume() {
        super.onResume();
        lazyLoad();
    }
}
